<?php declare(strict_types=1);

/**
 * @author      guosir
 * @copyright   2023-2025 owner
 **/

namespace Srv\Apps\Apis\Task\Ctl;

use Srv\Apps\Proto\DTO\Task\TaskTplAddDTO;
use Srv\Apps\Proto\DTO\Task\TaskTplEditDTO;
use Srv\Apps\Proto\DTO\Task\TaskTplListDTO;
use Srv\Apps\Proto\Enum\PlatformEnum;
use Srv\Apps\Proto\Enum\YesOrNoEnum;
use Srv\Apps\Proto\VO\Task\TaskTplListVO;
use Srv\Apps\Proto\VO\Task\TaskTplVO;
use Srv\Libs\Common\CommArray;
use Srv\Libs\Common\CommJson;
use Srv\Libs\Common\CommTime;
use Srv\Libs\Frame\ControllerAbstract;
use Srv\Libs\Frame\Page;
use Srv\Libs\Storage\DataMysql;

final class TaskTplCtl extends ControllerAbstract
{
    private ?DataMysql $DbAuto              = null;     // DB-Write

    /**
     * @return static
     * tag
     */
    final public static function tag():self
    {
        $thisObject                         = self::tagGet();
        if($thisObject instanceof self){
            $thisObject->DbAuto             = self::getDbAuto();
        }
        return $thisObject;
    }

    /**
     * @param int $tptkId
     * @return array
     * getTaskInfoSrc
     */
    public function getTaskTplInfoSrc(int $tptkId):array
    {
        if($tptkId < 1) return [];
        $sql    = 'SELECT tptk_id, tptk_platform, tptk_name, task_ids, tptk_status, tptk_create_time, tptk_update_time FROM '.$this->DbAuto->getTableNameAll('tpl_task_conf').' WHERE tptk_id='.$tptkId.' AND tptk_delete=0';
        $isFail = false;
        $info   = $this->DbAuto->getDataOne($sql, $isFail);
        if($isFail || !isset($info['tptk_id'])) return [];
        return $info;
    }

    /**
     * @param array $tptkIdList
     * @return array
     * getTaskInfoSrcBatch
     */
    public function getTaskInfoSrcBatch(array $tptkIdList):array
    {
        if(count($tptkIdList) < 1) return [];
        $isFail         = false;
        $list           = $this->DbAuto->getData('SELECT tptk_id, tptk_platform, tptk_name, task_ids, tptk_status, tptk_create_time, tptk_update_time FROM '.$this->DbAuto->getTableNameAll('tpl_task_conf').' WHERE tptk_id IN('.implode(',', $tptkIdList).') AND tptk_delete=0', $isFail);
        $listData       = [];
        if(!$isFail && CommArray::isForeach($list)) foreach ($list as $item){
            $tptkIdItem             = intval($item['tptk_id']??0);
            if($tptkIdItem < 1) continue;
            $listData[$tptkIdItem]  = $item;
        }
        return $listData;
    }

    /**
     * @param Page $Page
     * @param array $whereData
     * @return TaskTplListVO|null
     * getTaskTplList
     */
    public function getTaskTplList(Page $Page, array $whereData): ?TaskTplListVO
    {
        $limitString        = $Page->getLimitString();
        $whereString        = ' WHERE tptk_delete=0 ';
        // 检索条件
        if(count($whereData) > 0)foreach ($whereData as $key => $val){
            switch ($key){
                case TaskTplListDTO::_tptkId:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'tptk_id='. intval($val);
                    break;
                case TaskTplListDTO::_platform:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'tptk_platform='. intval($val);
                    break;
                case TaskTplListDTO::_name:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'tptk_name LIKE \'%'.$this->DbAuto->getRealEscapeString($val).'%\'';
                    break;
                case TaskTplListDTO::_status:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'tptk_status='. intval($val);
                    break;
            }
        }
        $isFail             = false;
        $sql                = 'SELECT SQL_CALC_FOUND_ROWS tptk_id, tptk_platform, tptk_name, task_ids, tptk_status, tptk_create_time, tptk_update_time FROM '.$this->DbAuto->getTableNameAll('tpl_task_conf').$whereString.' ORDER BY tptk_id DESC '.$limitString;
        $list               = $this->DbAuto->getData($sql, $isFail);
        $totalNum           = $this->DbAuto->getDataInt('SELECT FOUND_ROWS() as num', 'num');
        if($isFail) return null;
        $TaskTplVOList      = [];
        if(CommArray::isForeach($list))foreach($list as $item){
            $tptkIdItem             = intval($item['tptk_id']);
            if($tptkIdItem < 1) continue;
            $TaskTplVO              = $this->getTaskTplVO($item);
            if(!($TaskTplVO instanceof TaskTplVO)) continue;
            $TaskTplVOList[]        = $TaskTplVO;
        }
        $TaskTplListVO      = new TaskTplListVO();
        $TaskTplListVO->setList($TaskTplVOList);
        $TaskTplListVO->setPage($Page->getPageVO($totalNum));
        return $TaskTplListVO;
    }

    /**
     * @param array $info
     * @return TaskTplVO|null
     * getTaskTplVO
     */
    public function getTaskTplVO(array $info):?TaskTplVO
    {
        $tptkId         = intval($info['tptk_id']??0);
        if($tptkId < 1) return null;
        $TaskTplVO      = new TaskTplVO();
        $TaskTplVO->setTptkId($tptkId);
        $TaskTplVO->setPlatform(PlatformEnum::parseValue($info['tptk_platform']));
        $TaskTplVO->setTaskIds($info['task_ids']??'[]');
        $TaskTplVO->setName(trim($info['tptk_name']));
        $TaskTplVO->setStatus(YesOrNoEnum::parseValue($info['tptk_status']));
        $TaskTplVO->setCreateTime(intval($info['tptk_create_time']));
        $TaskTplVO->setUpdateTime(intval($info['tptk_update_time']));
        return $TaskTplVO;
    }

    /**
     * @param array $setData
     * @return int
     * taskTplAdd
     */
    public function taskTplAdd(array $setData):int
    {
        if(count($setData) < 1) return 0;
        $setString      = '';
        $taskIds        = '[]';
        foreach ($setData as $key => $val){
            switch ($key){
                case TaskTplAddDTO::_platform:
                    $setString      .= (strlen($setString) > 0?', ':'').'tptk_platform='.intval($val);
                    break;
                case TaskTplAddDTO::_name:
                    $setString      .= (strlen($setString) > 0?', ':'').'tptk_name=\''.$this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case TaskTplAddDTO::_taskIds:
                    if(!CommJson::isJsonString($val)) return 0;
                    $taskIds        = $val;
                    break;
                case TaskTplAddDTO::_status:
                    $setString      .= (strlen($setString) > 0?', ':'').'tptk_status='.intval($val);
                    break;
            }
        }
        if(strlen($setString) < 1) return 0;
        $currTime       = CommTime::getTimeStamp();
        $sql            = 'INSERT INTO '.$this->DbAuto->getTableNameAll('tpl_task_conf').' SET '.$setString.', task_ids=\''.$this->DbAuto->getRealEscapeString($taskIds).'\', tptk_delete=0, tptk_create_time='.$currTime.', tptk_update_time='.$currTime;
        return $this->DbAuto->getDataId($sql);
    }

    /**
     * @param int $tptkId
     * @param array $setData
     * @return bool
     * taskTplEdit
     */
    public function taskTplEdit(int $tptkId, array $setData):bool
    {
        if($tptkId < 1 || count($setData) < 1) return false;
        $setString      = '';
        foreach ($setData as $key => $val){
            switch ($key){
                case TaskTplEditDTO::_platform:
                    $setString      .= (strlen($setString) > 0?', ':'').'tptk_platform='.intval($val);
                    break;
                case TaskTplEditDTO::_name:
                    $setString      .= (strlen($setString) > 0?', ':'').'tptk_name=\''.$this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case TaskTplEditDTO::_taskIds:
                    if(!CommJson::isJsonString($val)) return false;
                    $setString      .= (strlen($setString) > 0?', ':'').'task_ids=\''.$this->DbAuto->getRealEscapeString($val).'\'';
                    break;
                case TaskTplEditDTO::_status:
                    $setString      .= (strlen($setString) > 0?', ':'').'tptk_status='.intval($val);
                    break;
            }
        }
        if(strlen($setString) < 1) return false;
        $currTime       = CommTime::getTimeStamp();
        $sql            = 'UPDATE '.$this->DbAuto->getTableNameAll('tpl_task_conf').' SET '.$setString.', tptk_update_time='.$currTime.' WHERE tptk_id='.$tptkId.' AND tptk_delete=0';
        return $this->DbAuto->getDataNum($sql)>0;
    }
}